package com.bl.file.util;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author yangxiaodong
 * @version 1.0
 * @description: TODO
 * @date 2025/7/2 13:47
 */
@Slf4j
public class UploadLogger {

    private final AtomicLong lastPrintTime = new AtomicLong(0);
    private final AtomicLong uploadedBytes = new AtomicLong(0);
    private final long totalBytes;
    private final long intervalMillis;

    public UploadLogger(long totalBytes, long intervalSeconds) {
        this.totalBytes = totalBytes;
        this.intervalMillis = intervalSeconds * 1000;
        this.lastPrintTime.set(System.currentTimeMillis());
    }

    public void onChunk(int bytes) {
        long current = uploadedBytes.addAndGet(bytes);
        long now = System.currentTimeMillis();
        long last = lastPrintTime.get();

        if (now - last >= intervalMillis) {
            lastPrintTime.set(now);
            if (totalBytes > 0) {
                int percent = (int) ((current * 100) / totalBytes);
                log.info("上传进度:{} , {} / {} bytes", percent, current, totalBytes);
            } else {
                log.info("已上传:{} bytes", current);
            }
        }
    }
}
